<?php
/**
 * Created by PhpStorm.
 * User: Charles
 * Date: 2017/10/8
 * Time: 1:30
 */

namespace app\Http\Controllers\Wechat;


use App\Http\Controllers\Controller;
use App\Models\EasyWechat;
use App\Models\Member;
use App\Models\MemberAccount;
use App\Models\UniqidOpenid;
use App\Models\WechatMember;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Overtrue\Socialite\AuthorizeFailedException;
use Overtrue\Socialite\User;

class OauthController extends Controller
{
    public function anyIndex(Request $request)
    {
        $oauth = EasyWechat::getApp()->oauth->setRequest($request);
        $redirectUrl = $request->redirect_url;
        $params = url_params($redirectUrl);
        if (!isset($params['domain'])) {
            die('Must Has Domain param!');
        }
        if (!isset($params['wechat_uniqid'])) {
            die('Must Has Wechat Uniqid param!');
        }
        try {
            $member = $oauth->user();
            $this->saveInfo($member, $params['wechat_uniqid']);
            // TODO
            return redirect(urldecode($request->redirect_url));
        } catch (AuthorizeFailedException $e) {
            Log::warning('微信Oauth用户认证失败，重新请求一次');
            return response()->redirectTo($redirectUrl);
        }
    }

    /**
     * 登录认证成功后，保存信息
     * @param User $member
     * @param $wechatUniqid
     */
    private function saveInfo(User $member, $wechatUniqid)
    {
        $openid = $member->getId();
        Session::put('wechat_uniqid', $wechatUniqid);
        Session::put('wechat_openid', $openid);

        $memberModel = Member::firstOrNew(['openid' => $openid]);
        $memberModel->easyWechatFill($member);
        $memberModel->save();
        Session::put('member', $memberModel);

        if (null == $memberModel->member_account) {
            $member_account = new MemberAccount();
            $member_account->openid = $member->getId();
            $member_account->save();
        }

        $uniqidOpenid = UniqidOpenid::firstOrNew(['uniqid' => $wechatUniqid]);
        $uniqidOpenid->openid = $member->getId();
        $uniqidOpenid->save();
    }
}